package threads;

import android.content.Context;
import android.os.Environment;
import android.os.Message;
import android.util.Log;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import constants.Constants;
import constants.HandlerConstant;
import customhandler.MyHandler;
import serialport.DealSerialPortData;
import singleton.SingletonClass;
import utils.CRCUtils;
import utils.DigitalTrans;
import utils.TimeUtil;

/**
 * Created by admin on 2017/11/21.
 */
public class SerialPortReadThread extends BaseThread {
    private InputStream mInputStream;
    private OutputStream mOutputStream;

    private DealSerialPortData dealSerialPortData;
    private StringBuilder sb = new StringBuilder();
    //收到的字节长度的总数
    private int count;
    //数据域长度
    private int dataLength;

    private ByteArrayOutputStream baos;
    private boolean isSend;
    private Context mContext;
    private MyHandler allHandler;
    private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
    private int length;

    // 584C4B4A0101011234567890ABAABBCCDDEEFFFFFFFFFFFFFF00112233445566778899BBCCDDEEFFFFFF011234567890ABAABBCCDDEEFF584C4B4A0101011234567890ABAABBCCDDEEFFFFFFFFFFFFFF0012233445566778899BBCCDDEEFFFFFF011234567890ABAABBCCDDEEFF
    public SerialPortReadThread(InputStream mInputStream, OutputStream mOutputStream, Context mContext) {
        this.mInputStream = mInputStream;
        this.mOutputStream = mOutputStream;
        this.mContext = mContext;
        dealSerialPortData = new DealSerialPortData(mOutputStream, mContext);
        allHandler = SingletonClass.getSingleton(MyHandler.class);
        baos = new ByteArrayOutputStream();
    }

    @Override
    public void run() {
        super.run();

        if (Constants.IS_OLD_ANDROID) {
            int size;
            while (!isInterrupted()) try {
                byte[] buffer = new byte[2048];
                if (mInputStream == null) {
                    return;
                }
//            Log.e("TAG", "hahahahahh: ");
                size = mInputStream.read(buffer);
//            Log.e("TAG", "run: "+ size);
                if (size > 0) {
                    Log.e("GGG", "send: ");
                    byte[] bs = new byte[size];

                    System.arraycopy(buffer, 0, bs, 0, size);
                    if (bs.length >= 24) {
                        //包头
                        if (bs[0] == 0x58 && bs[1] == 0x4C && bs[2] == 0x4B && bs[3] == 0x4A) {
                            baos.reset();
                            count = 0;
                            sb.delete(0, sb.length());
                            String s1 = DigitalTrans.toHexStringByte(bs[20]) + DigitalTrans.toHexStringByte(bs[21]);
                            dataLength = Integer.parseInt(s1, 16);
                        }
                    }

                    count += bs.length;
                    baos.write(bs, 0, bs.length);
                    byte[] bytes1 = baos.toByteArray();
                    //校验通过
                    String s11 = DigitalTrans.toHexString(bytes1);
                    Log.e("GGG", "run: " + s11);
                    if (count == (dataLength + 24)) {
//                    Log.e("TAG", "run: ");
                        byte[] bytes = baos.toByteArray();
                        //校验通过
                        String s1 = DigitalTrans.toHexString(bytes);

                        Log.e("TAG", "run: " + s1);
                        if (true) {
                            saveToFile(s1);
                            //发送一个完整的包
                            dealSerialPortData.receiveData(bytes);
//                        Log.e("BaseActivity", "run: "  );
                        }
                    } else {
                        Log.e("GGG", "run: send");
                        if (count > dataLength + 24) {
                            if (!isSend) {
                                isSend = true;
                                allHandler.sendEmptyMessageDelayed(HandlerConstant.SERIALPORT_SUBPACKAGE, 1000);
                            }
                        }
                    }
                    Thread.sleep(10);
                }
            } catch (IOException e) {
                e.printStackTrace();
                return;
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            runNewAndroid();
        }

    }

    private int number = 0;

    public void runNewAndroid() {

        int size;
        while (!isInterrupted()) try {
            byte[] buffer = new byte[1024];
            if (mInputStream == null) {
                return;
            }
//            Log.e("TAG", "hahahahahh: ");
            size = mInputStream.read(buffer);
//            Log.e("TAG", "run: "+ size);
            if (size > 0) {

                byte[] bs = new byte[size];
                System.arraycopy(buffer, 0, bs, 0, size);
                saveToFile(DigitalTrans.toHexString(bs));
                Log.e("GGG", "runNewAndroid: " + DigitalTrans.toHexString(bs));
                //包头
                if (bs[0] == 0x58) {
                    count = 0;
                    baos.reset();
                    baos.write(bs, 0, bs.length);
                    count += bs.length;
                    if (count >= 20) {
                        byte[] bytes = baos.toByteArray();
                        String s1 = DigitalTrans.toHexStringByte(bytes[20]) + DigitalTrans.toHexStringByte(bytes[21]);
                        dataLength = Integer.parseInt(s1, 16);
                    }
                } else {
                    baos.write(bs, 0, bs.length);
                    count += bs.length;
                    if (count >= 20) {
                        byte[] bytes = baos.toByteArray();
                        String s1 = DigitalTrans.toHexStringByte(bytes[20]) + DigitalTrans.toHexStringByte(bytes[21]);
                        dataLength = Integer.parseInt(s1, 16);
                    }
                }
//     58 4C4B4A0101011234567890AB012233445566         08 00 21 00 02 00 00 0E 3000E280681000000039D98381FB 3000E280681000000039D9828AB5  A217
                saveToFile(count + ":" + dataLength + "  " + 24);
                if (count == (dataLength + 24)) {
//                    Log.e("TAG", "run: ");
                    count = 0;
                    byte[] bytes = baos.toByteArray();

                    //校验通过
                    String s1 = DigitalTrans.toHexString(bytes);

//                    String count = DigitalTrans.toHexStringByte(bytes[bytes.length - 2]) + DigitalTrans.toHexStringByte(bytes[bytes.length - 1]);
//                    baos1.write(bytes,4,bytes.length - 6);
//                    byte[] b = baos1.toByteArray();
//                    char CRC1 = CRCUtils.getCrc(b, (byte) b.length);
//                    Log.e("TTT", "run: "+s1);
//                    Log.e("CRC", "runNewAndroid: " + DigitalTrans.toHexString(b) );
//                    Log.e("CRC", "onCreate: " + Integer.toHexString((int)CRC1).toUpperCase());
//                    Log.e("CRC", "run: " + count );
//                    baos1.reset();
//                    boolean check = count.equals(Integer.toHexString((int)CRC1).toUpperCase());

                    if (true) {
                        saveToFile(s1);
                        //发送一个完整的包
                        dealSerialPortData.receiveData(bytes);
//                        Log.e("BaseActivity", "run: "  );
                    } else {
                        allHandler.sendEmptyMessage(HandlerConstant.SERIAL_PORT_REPEAT);
                    }
                    baos.reset();
                } else {
                    if (count > dataLength + 24) {
                        if (!isSend) {
                            isSend = true;
                            allHandler.sendEmptyMessageDelayed(HandlerConstant.SERIALPORT_SUBPACKAGE, 1000);
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void saveToFile(String receiveData) {
        StringBuffer sb = new StringBuffer();
        try {
            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {

                String time = formatter.format(new Date());
                sb.append(time);
                sb.append("  --begin--:  ");
                sb.append(receiveData);
                sb.append("  --end--;  ");
                sb.append("\r\n");
                String fileName = TimeUtil.getYear() + "-" + (TimeUtil.getMonth() + 1) + "-" + TimeUtil.getDay() + ".log";
                String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/serialport/";
                File dir = new File(path);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                FileOutputStream fos = new FileOutputStream(path + fileName, true);
                fos.write(sb.toString().getBytes());
                fos.flush();
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void saveToFile1(String receiveData) {
        StringBuffer sb = new StringBuffer();
        try {
            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {

                String time = formatter.format(new Date());
                sb.append(time);
                sb.append("  --------------------:  ");
                sb.append(receiveData);
                sb.append("  --------------------;  ");
                sb.append("\r\n");
                String fileName = TimeUtil.getYear() + "-" + (TimeUtil.getMonth() + 1) + "-" + TimeUtil.getDay() + ".log";
                String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/serialport/";
                File dir = new File(path);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                FileOutputStream fos = new FileOutputStream(path + fileName, true);
                fos.write(sb.toString().getBytes());
                fos.flush();
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onHandleFrameMessage(Message msg) {
        switch (msg.what) {
            case HandlerConstant.SERIALPORT_SUBPACKAGE:
                saveToFile1("SERIALPORT_SUBPACKAGE");
                isSend = false;
                byte[] bytes = baos.toByteArray();

                String s1 = DigitalTrans.toHexString(bytes);
                saveToFile1(s1);
                String[] split = s1.split("584C4B4A");
                for (int i = 0; i < split.length; i++) {
                    if (split[i].length() >= 48) {
                        try {
                            saveToFile1("lengtg = " + split.length + "   " + i + "   584C4B4A" + split[i]);
                            //发送一个完整的包
                            dealSerialPortData.receiveData(DigitalTrans.hexStringToByteArray("584C4B4A" + split[i]));
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                baos.reset();
                break;
        }
    }

}
